package com.zixi.ai.framework.dao.spec;

import jakarta.persistence.criteria.*;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;

/**
 * @author mqiqe
 */
@Getter
public class FunctionExpression implements Criterion {
    //属性名
    private final String fieldName;
    //对应值
    private final Object value;
    //计算符
    private final Operator operator;
  
    protected FunctionExpression(String fieldName, Object value, Operator operator) {  
        this.fieldName = fieldName;  
        this.value = value;  
        this.operator = operator;  
    }
    @Override
	@SuppressWarnings({ "rawtypes"})  
    public Predicate toPredicate(Root<?> root, CriteriaQuery<?> query,
                                 CriteriaBuilder builder) {
        Path expression;
        if(fieldName.contains(".")){  
            String[] names = StringUtils.split(fieldName, ".");  
            expression = root.get(names[0]);  
            for (int i = 1; i < names.length; i++) {  
                expression = expression.get(names[i]);  
            }  
        }else{  
            expression = root.get(fieldName);  
        }
        return switch (operator) {
            case FUN_YEAR -> {
                Expression<Integer> year = builder.function("YEAR", Integer.class, expression);
                yield builder.equal(year, builder.literal(value));
            }
            case FUN_MONTH -> {
                Expression<Integer> month = builder.function("MONTH", Integer.class, expression);
                yield builder.equal(month, builder.literal(value));
            }
            default -> null;
        };
    }  
}
